﻿using UI00;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using DG.Tweening;
using System.IO;
using CSUtils;
using U3dComm;
using U3dUtils;
using UnityEngine.EventSystems;

namespace G12 {
    /// <summary>
    /// 第三层卡片
    /// </summary>
    public class CPreviewCard : MonoBehaviour {
        public static U3dObjectPool<string, CPreviewCard> objectPool = new U3dObjectPool<string, CPreviewCard>();
        public static string previewOnlyAssetsPath = "ImgPreview/Modle/14_Prop/CPreviewCard.prefab";

        public static void InitObjectPool() {
            objectPool.onGetNewObjEvent = delegate(string onlyAssetsPath) {
                var backBox = MainAssetsManager.LoadGo(onlyAssetsPath, 10);
                var selectCard = backBox.AddComponent<CPreviewCard>();
                selectCard.Init();
                selectCard.rectTransform.SetParent(objectPool.poolParent);
                return selectCard;
            };
            //o_ObjectPool.d_ObjRebornEvent = delegate (C_PreviewCard nn) {
            //    nn.gameObject.SetActive(true);
            //};
            objectPool.onObjDeathEvent = delegate(string cInt4, CPreviewCard nn) {
                //Debug.LogErrorFormat("C_PreviewCard.SetActive(false).________");
                nn.gameObject.SetActive(false);
            };
        }

        public RawImage videoImage;
        public RectTransform rectTransform, videoRectTransform, line;
        public VideoPlayer videoPlayer;
        Button closeButton;
        Transform dragButton;
        Text name;
        CUGUI uGUI0;

        void Init() {
            rectTransform = GetComponent<RectTransform>();
            videoImage = gameObject.transform.Find("video01").GetComponent<RawImage>();
            videoRectTransform = videoImage.GetComponent<RectTransform>();
            line = transform.Find("line").GetComponent<RectTransform>();
            videoPlayer = videoImage.GetComponent<VideoPlayer>();
            closeButton = videoImage.transform.Find("closeButton").GetComponent<Button>();
            dragButton = videoImage.transform.Find("dragButton");
            name = videoImage.transform.Find("name").GetComponent<Text>();
            line.localPosition = Vector3.zero;
            videoPlayer.playOnAwake = false;
            videoPlayer.source = VideoSource.Url;
            //  videoPlayer.url = "file:///" + assetsPath;
            videoPlayer.waitForFirstFrame = true;
            videoPlayer.sendFrameReadyEvents = true;
            bool isStartframe = true;
            videoPlayer.frameReady += delegate(VideoPlayer source, long frameIdx) {
                videoImage.texture = source.texture;
                if (isStartframe) {
                    isStartframe = false;
                    // sizeDelta = source.texture.texelSize;
                    sizeDelta = new Vector2(source.texture.width, source.texture.height);
                    _SetSize(radius / 2);
                }
            };
            closeButton.onClick.AddListener(delegate() {
                card.CancelSelect();
                //  S_Close();
            });
            uGUI0 = CUGUI.Get(rectTransform);
            uGUI0.onPress = delegate(CUGUI uGUI) {
                Debug.Log("C_PreviewCard__点击按下_________________" + file.assetsPath);
                _PressEvent(uGUI.pointerEventData);
            };
            uGUI0.onLift = delegate(CUGUI uGUI) {
                _LiftEvent(uGUI.pointerEventData);
            };
            uGUI0.onDragEvent = delegate(CUGUI uGUI) {
                _DragEvent(uGUI.pointerEventData);
            };
            var uGUI2 = CUGUI.Get(dragButton);
            uGUI2.onPress = delegate(CUGUI uGUI) {
                Debug.Log("C_PreviewCard_拖动按下_________________" + file.assetsPath);
                transform.SetSiblingIndex(10000);
                card.rectTransform.SetSiblingIndex(10000);
                isDraging = true;
                fingerPressPosi = uGUI.pointerEventData.position.ToVector3();
                fingerPressDistance = Vector3.Distance(transform.position, uGUI.pointerEventData.position.ToVector3());

                //UIBase.mono.StartCoroutine(I_DragZoom());
            };
            uGUI2.onLift = delegate(CUGUI uGUI) {
                isDraging = false;
                float zoomDistance = Vector3.Distance(transform.position, uGUI.pointerEventData.position.ToVector3());
                zoomSize = zoomSize * (zoomDistance / fingerPressDistance);
            };
            uGUI2.onDragEvent = delegate(CUGUI uGUI) {
                float zoomDistance = Vector3.Distance(transform.position, uGUI.pointerEventData.position.ToVector3());
                _SetSize((radius / 2) * zoomSize * (zoomDistance / fingerPressDistance));
            };
        }

        RectTransform currentSelectCard;
        Vector3 pressPosi, fingerPressPosi;

        public void _PressEvent(PointerEventData pointerEventData) {
            transform.SetSiblingIndex(10000);
            card.rectTransform.SetSiblingIndex(10000);
            currentSelectCard = rectTransform;
            fingerPressPosi = pointerEventData.position.ToVector3();
            pressPosi = currentSelectCard.position;
            // UIBase.mono.StartCoroutine(I_DragOffect());
        }

        public void _LiftEvent(PointerEventData pointerEventData) {
            currentSelectCard = null;
        }

        public void _DragEvent(PointerEventData pointerEventData) {
            Vector3 offect = pointerEventData.position.ToVector3() - fingerPressPosi;
            currentSelectCard.position = pressPosi + offect;

            _RefreshLine();
        }

        //IEnumerator 
        void _RefreshLine() {
            Vector3 v0 = card.rectTransform.position;
            Vector3 v1 = rectTransform.position;
            Vector3 vv = v0 - v1;
            float angle = Vector3.Angle(vv, Vector3.right);
            if (vv.y < 0) {
                angle = 360 - angle;
            }
            line.eulerAngles = new Vector3(0, 0, angle);
            float distance = Vector3.Distance(v0, v1);
            line.sizeDelta = new Vector2(distance, 35);
        }

        FileData file;
        float zoomSize;
        float fingerPressDistance;
        bool isDraging;

        float radius;
        CSelectCard.CCard0 card;

        public void Open(CSelectCard.CCard0 card, FileData file, Vector3 direction, float radius) {
            this.card = card;
            this.file = file;
            this.radius = radius;
            transform.SetParent(card.rectTransform);
            transform.position = card.rectTransform.position;
            rectTransform.sizeDelta = Vector2.one * radius;
            name.text = Path.GetFileName(file.assetsPath);
            zoomSize = 1;
            videoImage.texture = null;
            if (file.type == EFileType.img) {
                CAssetsLoad.SWWW(UIBase.mono, "file:///" + file.assetsPath, delegate(WWW www) {
                    if (www == null) {
                        Debug.LogErrorFormat("读取图片错误__{0}__", file.assetsPath);
                        videoImage.texture = null;
                    } else {
                        Texture2D tt = www.texture;
                        //  tt.format = TextureFormat.ARGB32;
                        videoImage.texture = tt;
                        // sizeDelta = www.texture.texelSize;
                        sizeDelta = new Vector2(www.texture.width, www.texture.height);
                        _SetSize(radius / 2);
                    }
                });
            } else if (file.type == EFileType.video) {
                videoPlayer.url = "file:///" + file.assetsPath;
                videoPlayer.Play();
            }
            transform.localScale = Vector3.one * 0.3f;
            transform.DOScale(Vector3.one, 0.3f);
            //Debug.LogErrorFormat("C_PreviewCard.SetActive(false).________");
            line.gameObject.SetActive(false);
            transform.DOMove(transform.position + direction * radius, 0.3f).
                OnComplete(delegate() {
                    line.gameObject.SetActive(true);
                    _RefreshLine();
                });
        }

        Vector2 sizeDelta;

        void _SetSize(float radius) {
            Vector2 size;
            float thumbnailLenght = radius * 1.6f;
            if (sizeDelta.x >= sizeDelta.y) {
                size = new Vector2(thumbnailLenght, sizeDelta.y * thumbnailLenght / sizeDelta.x);
            } else {
                size = new Vector2(sizeDelta.x * thumbnailLenght / sizeDelta.y, thumbnailLenght);
            }
            //Vector2 size = new Vector2(texture.width, texture.height) * 512 / C_Ttttt.thumbnailLenght;
            videoRectTransform.sizeDelta = size;
            rectTransform.sizeDelta = size + Vector2.one * 40; // Vector2.one* thumbnailLenght;
        }

        public void Close() {
            transform.localScale = Vector3.one;
            transform.DOScale(Vector3.one * 0.3f, 0.3f);
            //Debug.LogErrorFormat("C_PreviewCard.SetActive(false)._______3_");
            line.gameObject.SetActive(false);
            transform.DOMove(card.rectTransform.position, 0.3f).
                OnComplete(delegate() {
                    objectPool.SetToDeathList(previewOnlyAssetsPath, this);
                });
        }
    }
}
